<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus'
import {
  reqFindSupermarket,
  reqaddSupermarket,
  reqAcceptedFixApply,
  reqRemoveSupermarket,
} from '@/api/repair';
import {
    CirclePlus
} from '@element-plus/icons-vue';
import { AddParams, listItem } from './types';
import { reqUploadPic } from '@/api/message';
import { useStore } from '@/pinna';
import { useRoute } from 'vue-router';
const infoStore = useStore()
onMounted(() => {
  findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)

const handleSizeChange = (val: number) => {
  pageSize.value = val
  findData()
}

const handleCurrentChange = (val: number) => {
  pageNo.value = val
  findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<listItem[]>> = ref([])

const findData = async () => {
  await reqFindSupermarket({
    pageNo: toValue(pageNo),
    pageSize: toValue(pageSize),
  }).then((res: any) => {
    const { code, data, total: tableTotal } = res

    if (code === 200) {
      tableData.value = data
      total.value = tableTotal

    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

// 添加社区资讯弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加')
const formLabelWidth = '100px'
const addHsotForm: Ref<AddParams> = ref({
  applyName: "",
  applyReason: "",
  applyPic: "",
  remark: '',
  isAccepted: '0'
})

const resetDialogHostFrom = () => {
  fileList.value = []
  addHsotForm.value = {
    applyName: "",
    applyReason: "",
    applyPic: "",
    remark: '',
    isAccepted: '0'
  }
}


const addHostSubmit = async () => {
  if (dialogHostTitle.value == '添加') {
    await reqaddSupermarket({ ...unref(addHsotForm), isAccepted: +unref(addHsotForm).isAccepted }).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost1.value = false
        findData()
        ElMessage({
          message: '添加成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '受理') {
    await reqAcceptedFixApply({ ...unref(addHsotForm), id: unref(editId), isAccepted: +unref(addHsotForm).isAccepted }).then((res: any) => {
      if (res.code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '受理成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })

  }

}

let editId = ref('')
const updateHostDialog = async (id: string) => {
  resetDialogHostFrom()
  dialogHostTitle.value = '受理'
  dialogHost.value = true
  editId.value = id
}

const deleteHostDialog = async (id: string) => {
  ElMessageBox.confirm(
    '是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await reqRemoveSupermarket({ id }).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
          findData()
        } else {
          ElMessage({
            message: '请求异常',
            type: 'warning'
          })
        }
      })
    })

}

let fileList = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const updataImg = async (data: any) => {
  await reqUploadPic({ image: data.file }).then((res: any) => {
    addHsotForm.value.applyPic = res.data
  })
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  addHsotForm.value.applyPic = ''
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const isReadonlyHandler = computed(() => {
  return dialogHostTitle.value !== '查看'
})

const route = useRoute();
const isRouterUser = computed(() => {
  return route.path.includes('reception')
})

let dialogHost1 = ref(false)
const addHostDialog = () => {
    resetDialogHostFrom()
    dialogHostTitle.value = '添加'
    dialogHost1.value = true
}
</script>

<template>
  <el-card>
    <template v-if="!isRouterUser" #header>
      <div class="card-header">
        <span><strong>{{ infoStore.$state.info.role == 'admin' ? '维修申请管理' : '维修查看' }}</strong></span>
      </div>
    </template>
    <el-button v-if="isRouterUser" key="'添加维修申请'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
        class="addUser">
        添加维修申请
      </el-button>
  </el-card>
  <div class="card-layout" v-if="isRouterUser">
    <el-card class="layout-style" v-for="(row, index) in tableData" style="max-width: 480px;width: 32%;height: 480px;">
      <template #header>
        <div class="card-header">
          <span>{{ '维修描述列表' +(index + 1)}}</span>
        </div>
      </template>
      <div style="height:290px;overflow: auto;">
        <p class="text item">{{ '申请人: ' + row?.applyName }}</p>
        <p class="text item">{{ '申请原因: ' + row?.applyReason }}</p>
        <p class="text item">{{ '是否受理: ' + (row?.isAccepted == 0 ? '否' : '是')  }}</p>
        <p class="text item">{{ '受理时间: ' + row?.acceptedTime }}</p>
        <p class="text item">{{ '受理时间: ' + row?.acceptedTime }}</p>
        <div class="text item">
          <span>维修图片： </span>
          <el-image style="width: 50px; height: 50px" :src="row?.applyPic" :fit="'contain'">
            <template #error>
              <div style="width: 100%;height: 100%;display: flex;align-items: center;">
                无图片
              </div>
            </template></el-image>
          </div>

      </div>

      <template #footer>
        <p style="color: blue;font-size: 12px;float: right;">{{ '申请时间: ' + (row?.applyTime || '空') }}</p>
      </template>
    </el-card>
  </div>
  <el-card v-else>
    <!-- <div>
      <el-button key="'添加维修申请'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
        class="addUser">添加维修申请</el-button>
    </div> -->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="applyName" label="申请人" />
      <el-table-column prop="applyTime" label="申请时间" />
      <el-table-column prop="applyReason" label="申请原因" />
      <el-table-column prop="applyPic" label="申请图片">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.applyPic" :fit="'contain'"><template #error>
              <div style="width: 100%;height: 100%;display: flex;align-items: center;">
                无图片
              </div>
            </template></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="isAccepted" label="是否受理">
        <template #default="scope">
          <div>
            {{ scope.row.isAccepted == 0 ? '否' : '是' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="acceptedName" label="受理人姓名" />
      <el-table-column prop="acceptedTime" label="受理时间" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column fixed="right" label="操作" v-if="infoStore.$state.info.role == 'admin'">
        <template #default="scope">
          <el-space wrap>
            <el-button type="primary" size="small" plain v-if="scope.row.isAccepted == 0"
              @click="updateHostDialog(scope.row.id)">受理</el-button>
            <el-button type="primary" size="small" plain @click="deleteHostDialog(scope.row.id)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-card>
  <!-- 添加户主弹框 -->
  <el-dialog v-model="dialogHost" :title="dialogHostTitle">
    <el-form :model="addHsotForm">
      <div v-if="dialogHostTitle === '受理'">
        <el-form-item label="是否受理:" :label-width="formLabelWidth" clearable required>
          <el-radio-group v-model="addHsotForm.isAccepted" class="ml-4" :disabled="!isReadonlyHandler">
            <el-radio label="0" size="large">否</el-radio>
            <el-radio label="1" size="large">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注:" :label-width="formLabelWidth" clearable required>
          <el-input v-model="addHsotForm.remark" autocomplete="off" placeholder="请输入维修内容"
            :disabled="!isReadonlyHandler" />
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item label="申请人:" :label-width="formLabelWidth" clearable required>
          <el-input v-model="addHsotForm.applyName" autocomplete="off" placeholder="请输入申请人"
            :disabled="!isReadonlyHandler" />
        </el-form-item>
        <el-form-item label="申请原因:" :label-width="formLabelWidth" clearable required>
          <el-input v-model="addHsotForm.applyReason" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
            placeholder="请输入申请原因" :disabled="!isReadonlyHandler" />
        </el-form-item>
        <el-form-item label="图片:" :label-width="formLabelWidth" clearable v-if="isReadonlyHandler">
          <el-upload v-model:file-list="fileList" :http-request="updataImg" :limit="1"
            :headers="{ 'Content-Type': 'multipart/form-data' }" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :disabled="!isReadonlyHandler">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogHost = false">取消</el-button>
        <el-button v-if="isReadonlyHandler" type="primary" @click="addHostSubmit()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogHost1" :title="dialogHostTitle">
        <el-form :model="addHsotForm">
            <div>
                <el-form-item label="申请人:" :label-width="formLabelWidth" clearable required>
                    <el-input v-model="addHsotForm.applyName" autocomplete="off" placeholder="请输入申请人"
                        :disabled="!isReadonlyHandler" />
                </el-form-item>
                <el-form-item label="申请原因:" :label-width="formLabelWidth" clearable required>
                    <el-input v-model="addHsotForm.applyReason" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                        placeholder="请输入申请原因" :disabled="!isReadonlyHandler" />
                </el-form-item>
                <el-form-item label="图片:" :label-width="formLabelWidth" clearable v-if="isReadonlyHandler">
                    <el-upload v-model:file-list="fileList" :http-request="updataImg" :limit="1"
                        :headers="{ 'Content-Type': 'multipart/form-data' }" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost1 = false">取消</el-button>
                <el-button type="primary" @click="addHostSubmit()">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-input {
  margin-right: 5px;
  width: 400px;
}

.query-input {
  display: flex;
  gap: 10;
}

.el-card {
  margin-bottom: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.addUser {
  /* float: right; */
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
  width: 400px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.card-layout {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-around;
}
.layout-style:hover {
    box-shadow: 5px 5px 5px rgb(170, 166, 166);
  }
</style>